<template>
    <div class="glass-background min-h-screen flex items-center justify-center font-sans text-glass-text">
        <div class="w-full max-w-md">
            <!-- Logo 区域 -->
            <div class="text-center mb-8">
                <div class="w-16 h-16 glass-card rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-robot text-glass-primary text-2xl"></i>
                </div>
                <h1 class="text-3xl font-bold text-glass-text mb-2">AI Chat</h1>
                <p class="text-glass-text-muted">智能对话助手</p>
            </div>

            <!-- 注册表单 -->
            <div class="login-container rounded-xl shadow-lg p-8">
                <h2 class="text-2xl font-semibold text-glass-text mb-6 text-center">创建新账户</h2>

                <!-- 错误提示 -->
                <div v-if="errorMessage" class="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded-lg">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    {{ errorMessage }}
                </div>

                <!-- 成功提示 -->
                <div v-if="successMessage"
                    class="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded-lg">
                    <i class="fas fa-check-circle mr-2"></i>
                    {{ successMessage }}
                </div>

                <form @submit.prevent="handleRegister" class="space-y-6">
                    <!-- 用户名输入 -->
                    <div>
                        <label for="username" class="block text-sm font-medium text-glass-text mb-2">用户名</label>
                        <div class="relative">
                            <input type="text" id="username" name="username" required v-model="registerForm.username"
                                :disabled="isLoading"
                                class="glass-input w-full px-4 py-3 rounded-lg outline-none transition-all duration-200 text-glass-text placeholder-glass-text-muted disabled:bg-gray-100 disabled:cursor-not-allowed"
                                placeholder="请输入用户名" @blur="validateUsername">
                            <i
                                class="fas fa-user absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted"></i>
                        </div>
                        <p v-if="usernameError" class="text-red-500 text-sm mt-1">{{ usernameError }}</p>
                    </div>

                    <!-- 邮箱输入 -->
                    <div>
                        <label for="email" class="block text-sm font-medium text-glass-text mb-2">邮箱地址</label>
                        <div class="relative">
                            <input type="email" id="email" name="email" required v-model="registerForm.email"
                                :disabled="isLoading"
                                class="glass-input w-full px-4 py-3 rounded-lg outline-none transition-all duration-200 text-glass-text placeholder-glass-text-muted disabled:bg-gray-100 disabled:cursor-not-allowed"
                                placeholder="请输入您的邮箱地址" @blur="validateEmail">
                            <i
                                class="fas fa-envelope absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted"></i>
                        </div>
                        <p v-if="emailError" class="text-red-500 text-sm mt-1">{{ emailError }}</p>
                    </div>

                    <!-- 密码输入 -->
                    <div>
                        <label for="password" class="block text-sm font-medium text-glass-text mb-2">密码</label>
                        <div class="relative">
                            <input :type="showPassword ? 'text' : 'password'" id="password" name="password" required
                                v-model="registerForm.password" :disabled="isLoading"
                                class="glass-input w-full px-4 py-3 rounded-lg outline-none transition-all duration-200 text-glass-text placeholder-glass-text-muted disabled:bg-gray-100 disabled:cursor-not-allowed"
                                placeholder="请输入密码（至少6位）" @blur="validatePassword">
                            <button type="button" @click="togglePasswordVisibility"
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted hover:text-glass-text transition-colors">
                                <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                            </button>
                        </div>
                        <p v-if="passwordError" class="text-red-500 text-sm mt-1">{{ passwordError }}</p>
                    </div>

                    <!-- 确认密码输入 -->
                    <div>
                        <label for="confirmPassword" class="block text-sm font-medium text-glass-text mb-2">确认密码</label>
                        <div class="relative">
                            <input :type="showConfirmPassword ? 'text' : 'password'" id="confirmPassword"
                                name="confirmPassword" required v-model="registerForm.confirmPassword"
                                :disabled="isLoading"
                                class="glass-input w-full px-4 py-3 rounded-lg outline-none transition-all duration-200 text-glass-text placeholder-glass-text-muted disabled:bg-gray-100 disabled:cursor-not-allowed"
                                placeholder="请再次输入密码" @blur="validateConfirmPassword">
                            <button type="button" @click="toggleConfirmPasswordVisibility"
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted hover:text-glass-text transition-colors">
                                <i :class="showConfirmPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                            </button>
                        </div>
                        <p v-if="confirmPasswordError" class="text-red-500 text-sm mt-1">{{ confirmPasswordError }}</p>
                    </div>

                    <!-- 服务条款 -->
                    <div class="flex items-start">
                        <input type="checkbox" id="agreement" v-model="agreeToTerms" :disabled="isLoading"
                            class="w-4 h-4 text-glass-text bg-glass-bg border-glass-border rounded focus:ring-glass-primary mt-1 disabled:cursor-not-allowed">
                        <label for="agreement" class="ml-2 text-sm text-glass-text-muted">
                            我已阅读并同意
                            <a href="#" class="text-glass-text hover:text-glass-primary transition-colors">服务条款</a>
                            和
                            <a href="#" class="text-glass-text hover:text-glass-primary transition-colors">隐私政策</a>
                        </label>
                    </div>
                    <p v-if="agreementError" class="text-red-500 text-sm">{{ agreementError }}</p>

                    <!-- 注册按钮 -->
                    <button type="submit" :disabled="isLoading || !isFormValid"
                        class="glass-button w-full text-glass-text font-semibold py-3 px-4 rounded-lg transition-all duration-200 disabled:bg-gray-400 disabled:cursor-not-allowed">
                        <i v-if="isLoading" class="fas fa-spinner fa-spin mr-2"></i>
                        <i v-else class="fas fa-user-plus mr-2"></i>
                        {{ isLoading ? '注册中...' : '创建账户' }}
                    </button>

                    <!-- 分割线 -->
                    <div class="relative my-6">
                        <div class="absolute inset-0 flex items-center">
                            <div class="w-full border-t border-glass-border"></div>
                        </div>
                        <div class="relative flex justify-center text-sm">
                            <span class="px-2 bg-transparent text-glass-text-muted">或者</span>
                        </div>
                    </div>

                    <!-- 第三方登录 -->
                    <div class="space-y-3">
                        <button type="button" @click="handleOAuthRegister('google')" :disabled="isLoading"
                            class="glass-button w-full flex items-center justify-center px-4 py-3 rounded-lg transition-colors text-glass-text disabled:bg-gray-100 disabled:cursor-not-allowed">
                            <svg class="w-5 h-5 mr-3" viewBox="0 0 24 24">
                                <path fill="#4285F4"
                                    d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                <path fill="#34A853"
                                    d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                <path fill="#FBBC05"
                                    d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                <path fill="#EA4335"
                                    d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                            </svg>
                            使用 Google 注册
                        </button>

                        <button type="button" @click="handleOAuthRegister('microsoft')" :disabled="isLoading"
                            class="glass-button w-full flex items-center justify-center px-4 py-3 rounded-lg transition-colors text-glass-text disabled:bg-gray-100 disabled:cursor-not-allowed">
                            <i class="fab fa-microsoft text-blue-600 text-lg mr-3"></i>
                            使用 Microsoft 注册
                        </button>
                    </div>

                    <!-- 登录链接 -->
                    <div class="text-center mt-6">
                        <p class="text-sm text-glass-text-muted">
                            已有账户？
                            <router-link to="/login"
                                class="text-glass-text hover:text-glass-primary font-medium transition-colors">
                                立即登录
                            </router-link>
                        </p>
                    </div>
                </form>
            </div>

            <!-- 底部信息 -->
            <div class="text-center mt-8 text-sm text-glass-text-muted">
                <p>© 2024 AI Chat. 保留所有权利.</p>
                <div class="mt-2 space-x-4">
                    <a href="#" class="hover:text-glass-text transition-colors">服务条款</a>
                    <a href="#" class="hover:text-glass-text transition-colors">隐私政策</a>
                    <a href="#" class="hover:text-glass-text transition-colors">帮助</a>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { registerAPI, getOauthUrlAPI, type RegisterRequest } from '@/http/chatAPI'

const router = useRouter()

// 响应式数据
const isLoading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const usernameError = ref('')
const emailError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const agreementError = ref('')
const agreeToTerms = ref(false)

// 注册表单数据
const registerForm = ref<RegisterRequest>({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
})

// 计算属性
const isFormValid = computed(() => {
    return registerForm.value.username &&
        registerForm.value.email &&
        registerForm.value.password &&
        registerForm.value.confirmPassword &&
        !usernameError.value &&
        !emailError.value &&
        !passwordError.value &&
        !confirmPasswordError.value &&
        agreeToTerms.value
})

// 用户名验证
const validateUsername = () => {
    if (!registerForm.value.username) {
        usernameError.value = '请输入用户名'
    } else if (registerForm.value.username.length < 2) {
        usernameError.value = '用户名至少2个字符'
    } else if (registerForm.value.username.length > 20) {
        usernameError.value = '用户名不能超过20个字符'
    } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(registerForm.value.username)) {
        usernameError.value = '用户名只能包含字母、数字、下划线和中文'
    } else {
        usernameError.value = ''
    }
}

// 邮箱验证
const validateEmail = () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!registerForm.value.email) {
        emailError.value = '请输入邮箱地址'
    } else if (!emailRegex.test(registerForm.value.email)) {
        emailError.value = '请输入有效的邮箱地址'
    } else {
        emailError.value = ''
    }
}

// 密码验证
const validatePassword = () => {
    if (!registerForm.value.password) {
        passwordError.value = '请输入密码'
    } else if (registerForm.value.password.length < 6) {
        passwordError.value = '密码长度至少6位'
    } else if (registerForm.value.password.length > 50) {
        passwordError.value = '密码长度不能超过50位'
    } else if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(registerForm.value.password)) {
        passwordError.value = '密码必须包含字母和数字'
    } else {
        passwordError.value = ''
    }

    // 如果确认密码已输入，重新验证确认密码
    if (registerForm.value.confirmPassword) {
        validateConfirmPassword()
    }
}

// 确认密码验证
const validateConfirmPassword = () => {
    if (!registerForm.value.confirmPassword) {
        confirmPasswordError.value = '请确认密码'
    } else if (registerForm.value.password !== registerForm.value.confirmPassword) {
        confirmPasswordError.value = '两次输入的密码不一致'
    } else {
        confirmPasswordError.value = ''
    }
}

// 切换密码可见性
const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value
}

// 切换确认密码可见性
const toggleConfirmPasswordVisibility = () => {
    showConfirmPassword.value = !showConfirmPassword.value
}

// 清除消息
const clearMessages = () => {
    errorMessage.value = ''
    successMessage.value = ''
}

// 处理注册
const handleRegister = async () => {
    clearMessages()

    // 验证表单
    validateUsername()
    validateEmail()
    validatePassword()
    validateConfirmPassword()

    // 验证服务条款
    if (!agreeToTerms.value) {
        agreementError.value = '请同意服务条款和隐私政策'
        return
    } else {
        agreementError.value = ''
    }

    if (!isFormValid.value) {
        return
    }

    isLoading.value = true

    try {
        const response = await registerAPI(registerForm.value)

        if (response.data && response.data.code == 200) {
            successMessage.value = '注册成功！正在跳转到登录页面...'

            // 延迟跳转以显示成功消息
            setTimeout(() => {
                router.push('/login')
            }, 2000)
        }

        successMessage.value = '注册成功！正在跳转到登录页面...'

        // 延迟跳转以显示成功消息
        setTimeout(() => {
            router.push('/login')
        }, 2000)

    } catch (error: any) {
        errorMessage.value = error.message || '注册失败，请重试'
    } finally {
        isLoading.value = false
    }
}

// 处理第三方注册
const handleOAuthRegister = async (provider: string) => {
    try {
        isLoading.value = true
        const response = await getOauthUrlAPI(provider, window.location.origin + '/auth/callback')
        window.location.href = response.url
    } catch (error: any) {
        errorMessage.value = error.message || `${provider} 注册失败`
        isLoading.value = false
    }
}

// // 检查是否已登录
// onMounted(() => {
//     const token = localStorage.getItem('token')
//     if (token) {
//         router.push('/')
//     }
// })
</script>

<style scoped>
/* 自定义样式 */
.font-sans {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
}

/* 毛玻璃效果样式 */
.glass-background {
    background: linear-gradient(135deg, #f0f2f5 0%, #ffffff 50%, #f8f9fa 100%);
    min-height: 100vh;
}

.glass-effect {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.glass-card {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.glass-button {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.glass-button:hover:not(:disabled) {
    background: rgba(255, 255, 255, 0.95);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.glass-input {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.glass-input:focus {
    background: rgba(255, 255, 255, 0.95);
    border-color: rgba(0, 0, 0, 0.2);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-container {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.8) 100%);
    backdrop-filter: blur(30px);
    border: 1px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

/* 颜色变量 */
:root {
    --glass-light: #ffffff;
    --glass-light-secondary: #f8f9fa;
    --glass-dark: #1a1a1a;
    --glass-border: rgba(0, 0, 0, 0.08);
    --glass-primary: #000000;
    --glass-primary-hover: rgba(0, 0, 0, 0.8);
    --glass-secondary: #ffffff;
    --glass-text: #1f2937;
    --glass-text-muted: rgba(31, 41, 55, 0.7);
    --glass-bg: rgba(255, 255, 255, 0.7);
    --glass-bg-hover: rgba(255, 255, 255, 0.9);
    --glass-shadow: rgba(0, 0, 0, 0.1);
}

/* Tailwind自定义颜色类 */
.text-glass-primary {
    color: var(--glass-primary);
}

.text-glass-text {
    color: var(--glass-text);
}

.text-glass-text-muted {
    color: var(--glass-text-muted);
}

.bg-glass-bg {
    background-color: var(--glass-bg);
}

.border-glass-border {
    border-color: var(--glass-border);
}

.focus\:ring-glass-primary:focus {
    --tw-ring-color: var(--glass-primary);
}

.hover\:text-glass-primary:hover {
    color: var(--glass-primary);
}

.placeholder-glass-text-muted::placeholder {
    color: var(--glass-text-muted);
}

/* 输入框聚焦效果 */
input:focus {
    box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.1);
}

/* 按钮悬停效果 */
button:hover:not(:disabled) {
    transform: translateY(-1px);
}

/* 加载动画 */
@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.fa-spin {
    animation: spin 1s linear infinite;
}

/* 响应式设计 */
@media (max-width: 640px) {
    .max-w-md {
        margin: 1rem;
    }
}
</style>
